#include "Thread.h"
#include <stdio.h>

//=================新加========================
__thread const char *name = "current_thread";

Thread::Thread(ThreadCallback &&cb, const string &name)
: _thid(0)
, _name(name)
, _isRunning(false)
, _cb(std::move(cb)){ // 回调函数的注册
}


Thread::~Thread(){}


//线程运行函数
void Thread::start(){
    // 
    int ret = pthread_create(&_thid, nullptr, threadFunc, this);
    if(ret){
        perror("pthread_create");
        return;
    }
    _isRunning = true;//线程在运行了
}


// 线程退出函数
void Thread::join(){
    if(_isRunning){
        int ret = pthread_join(_thid, nullptr);
        if(ret){
            perror("pthread_join");
            return;
        }
        _isRunning = false;
    }
}


// 线程入口函数
void *Thread::threadFunc(void *arg){
    Thread *pth = static_cast<Thread *>(arg); // 
    //==============新加===================
    name = pth->_name.c_str();//从string转换为const char *
    if(pth){
        pth->_cb();// 体现出来了多态
    }

    /* return nullptr; */
    pthread_exit(nullptr);
}

